package org.jeecg.modules.xl.logicmana.service;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logitrace;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogitraceService;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 自动物流轨迹
 *

 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class AutoLogiTrackJob implements Job {
    @Resource
    private IXlCustomerLogisticPackageService xlCustomerLogisticPackageService;

    @Resource
    private IXlKuaidi100LogitraceService iXlKuaidi100LogitraceService;

    @Resource
    private IXlCustomerOrdeService ordeService;

    @Autowired
    private XlLogUtil xlLogUtil ;

    @Resource
    private IXlCustomerLogisticPackageService packageService;

    String key = "apCDGXjp8152";
    String customer = "3E163C1F545E1D6C38EC8DABE13293B3";
    String secret ="c28bd653d6bc405288bb31ffe799e741";
    String userid =  "c28bd653d6bc405288bb31ffe799e741";
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(" --- 同步任务调度开始 --- ");
        final TimeInterval timeInterval = new TimeInterval();
        XlCustomerLogisticPackage xlCustomerLogisticPackage = new XlCustomerLogisticPackage();
        QueryWrapper<XlCustomerLogisticPackage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_check",0);//未签收的五六点
        //queryWrapper.lt("create_time", DateUtil.offsetDay(DateUtil.date(), -1));//1天前的物流记录
        Page<XlCustomerLogisticPackage> page = new Page<>(1, 80);
        //取 20条数据
        IPage<XlCustomerLogisticPackage> pageList = xlCustomerLogisticPackageService.page(page, queryWrapper);
        if (ObjectUtil.isNotEmpty(pageList) && ObjectUtil.isNotEmpty(pageList.getRecords())) {
            for (XlCustomerLogisticPackage xlCustomerLogisticTemp : pageList.getRecords()) {
                String logiCom = xlCustomerLogisticTemp.getLogiCom();
                //处理没有物流单号的异常数据，直接删除
                if(ObjectUtil.isEmpty(xlCustomerLogisticTemp.getLogiOrder())){
                    xlCustomerLogisticPackageService.removeById(xlCustomerLogisticTemp.getId());
                    continue;
                }
                XlCustomerOrde  customerOrdeTarget =   ordeService.getOneByCode(xlCustomerLogisticTemp.getOrderCode());
                if(ObjectUtil.isEmpty(customerOrdeTarget)){
                    xlCustomerLogisticPackageService.removeById(xlCustomerLogisticTemp.getId());
                    continue;
                }
                if("已收货".equals(customerOrdeTarget.getOrderStatus())){
                    autoSetOrderStatusToReceived(xlCustomerLogisticTemp.getOrderCode(), xlCustomerLogisticTemp.getLogiOrder());
                }
                if("已付款".equals(customerOrdeTarget.getOrderStatus())){
                    autoSetOrderStatusToReceived(xlCustomerLogisticTemp.getOrderCode(), xlCustomerLogisticTemp.getLogiOrder());
                }

                //处理城市配送
                if("chengshipeisong".equals(logiCom)||"CSPS".equals(logiCom)||"城市配送".equals(logiCom)||"XSPS".equals(logiCom)){
                    //15天前城市配送订单自动收货
                    if( DateUtil.between(DateUtil.date(),xlCustomerLogisticTemp.getCreateTime(), DateUnit.DAY ) > 2 ){
                        autoSetOrderStatusToReceived(xlCustomerLogisticTemp.getOrderCode(), xlCustomerLogisticTemp.getLogiOrder());
                    }
                    continue;
                }
                //处理快递
                QueryTrackReq queryTrackReq = new QueryTrackReq();
                QueryTrackParam queryTrackParam = new QueryTrackParam();
                queryTrackParam.setCom(xlCustomerLogisticTemp.getLogiCom());
                queryTrackParam.setNum(xlCustomerLogisticTemp.getLogiOrder());
                queryTrackParam.setResultv2("4");
                String param = new Gson().toJson(queryTrackParam);

                queryTrackReq.setParam(param);
                queryTrackReq.setCustomer(customer);
                queryTrackReq.setSign(SignUtils.querySign(param, key, customer));

                IBaseClient baseClient = new QueryTrack();
                //System.out.println(baseClient.execute(queryTrackReq));
                HttpResult result = null;
                try {
                    result = baseClient.execute(queryTrackReq);
                } catch (Exception e) {
                   // throw new RuntimeException(e);
                    continue;
                }
                QueryTrackResp queryTrackResp = new Gson().fromJson(result.getBody(), QueryTrackResp.class);
                String qianshouTime = "";
                if (ObjectUtil.isNotEmpty(queryTrackResp.getData())) {
                    List<XlKuaidi100Logitrace> xlKuaidi100Logitraces = new ArrayList<>();
                    //用户已签收 ｜｜ 或者 疑难件，是快递的最终状态
                    if ("1".equals(queryTrackResp.getIscheck())||queryTrackResp.getState().startsWith("2")) {
                        for (QueryTrackData queryTrackData : queryTrackResp.getData()) {
                            if ("签收".equals(queryTrackData.getStatus())) {
                                qianshouTime = queryTrackData.getFtime();
                            }
                            XlKuaidi100Logitrace tracetemp = new XlKuaidi100Logitrace();
                            //tracetemp.setLogiCode(xlCustomerLogisticTemp.getOrderCode());
                            //bugfix 物流轨迹保存错误
                            tracetemp.setLogiCode(xlCustomerLogisticTemp.getLogiOrder());
                            tracetemp.setLogiComCode(queryTrackResp.getCom());
                            tracetemp.setStatuscode(queryTrackData.getStatusCode());
                            tracetemp.setStatus(queryTrackData.getStatus());
                            tracetemp.setTime(queryTrackData.getTime());
                            tracetemp.setFtime(queryTrackData.getFtime());
                            tracetemp.setContext(queryTrackData.getContext());
                            try {
                                iXlKuaidi100LogitraceService.save(tracetemp);
                            }catch (DuplicateKeyException e){
                                continue;
                            }

                            xlKuaidi100Logitraces.add(tracetemp);
                        }
                        //需要将物流轨迹落库
                        //iXlKuaidi100LogitraceService.saveOrUpdateBatch(xlKuaidi100Logitraces);
                        //自动更新订单为状态为 已签收
                        autoSetOrderStatusToReceived(xlCustomerLogisticTemp.getOrderCode(), xlCustomerLogisticTemp.getLogiOrder());
                    }
                }
            }
            log.info(" --- 执行完毕，消耗时间：" + timeInterval.intervalSecond() + "---");
        }
    }

    private void autoSetOrderStatusToReceived(String orderCode,String logiCode){
        //自动更新订单为状态为 已签收
        UpdateWrapper<XlCustomerOrde> ordeUpdateWrapper = new UpdateWrapper<>();
        ordeUpdateWrapper.set("order_status", "已收货")
                .eq("order_code", orderCode)
                .eq("order_status", "待收货");
        ordeService.update(ordeUpdateWrapper);
        //自动更新物流为状态为 已签收
        UpdateWrapper<XlCustomerLogisticPackage> xlCustomerLogisticPackageUpdateWrapper = new UpdateWrapper<>();
        xlCustomerLogisticPackageUpdateWrapper.set("is_check", "1")
                .set("update_time",DateUtil.date())
                .eq("logi_order", logiCode);
        packageService.update(xlCustomerLogisticPackageUpdateWrapper);
        xlLogUtil.insertLog(orderCode, "签收", "系统抓取物流轨迹签收", new Date(), "待收货", "已收货");
    }
}
